package edu.npu.cv.controller.rest;

import edu.npu.cv.constant.ConstantHolder;
import edu.npu.cv.constant.ResultCode;
import edu.npu.cv.constant.TemplatePath;
import edu.npu.cv.constant.URLConstant;
import edu.npu.cv.entity.ResultDO;
import edu.npu.cv.utils.UrlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName UploadRestController
 * @Description 文件上传通用rest接口
 * @Author Quentin_zyj
 * @Date 2021/10/13 19:08
 */
@Slf4j
@RestController
@RequestMapping(URLConstant.S + URLConstant.UPLOAD)
public class UploadRestController {

    @PostMapping(URLConstant.UPLOAD_UPLOAD_FILE)
    public ResultDO<Object> upload(HttpServletRequest httpServletRequest, MultipartFile file)
        throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        File fileDirectory = new File(ConstantHolder.FILE_UPLOAD_DIC);
        // 创建文件
        File destFile = new File(ConstantHolder.FILE_UPLOAD_DIC + newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            return new ResultDO<Object>(true, ResultCode.SUCCESS, ResultCode.MSG_SUCCESS,
                UrlUtil.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" + newFileName);

        } catch (IOException e) {

            return new ResultDO<Object>(false, ResultCode.ERROR_SYSTEM_EXCEPTION,
                ResultCode.MSG_ERROR_ACCOUNT_OR_PASSWORD, null);
        }
    }

    @PostMapping(URLConstant.MD + TemplatePath.S + URLConstant.MD_UPLOAD_FILE)
    public void uploadFileByEditormd(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(name = "editormd-image-file", required = true) MultipartFile file)
        throws IOException, URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        // 生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        // 创建文件
        File destFile = new File(ConstantHolder.FILE_UPLOAD_DIC + newFileName);
        String fileUrl = UrlUtil.getHost(new URI(request.getRequestURL() + "")) + "/upload/" + newFileName;
        File fileDirectory = new File(ConstantHolder.FILE_UPLOAD_DIC);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    log.info("文件夹创建失败"+ fileDirectory);
                    throw new IOException("文件夹创建失败,路径为：" + fileDirectory);
                }
            }
            file.transferTo(destFile);
            request.setCharacterEncoding("utf-8");
            response.setHeader("Content-Type", "text/html");
            response.getWriter().write("{\"success\": 1, \"message\":\"success\",\"url\":\"" + fileUrl + "\"}");
        } catch (UnsupportedEncodingException e) {
            response.getWriter().write("{\"success\":0}");
        } catch (IOException e) {
            response.getWriter().write("{\"success\":0}");
        }

    }

}
